<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="fonts/iconfont.css">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="css/car.css">
    <script src="libs/bootstrap/js/bootstrap.bundle.js"></script>
    <link rel="stylesheet" href="libs/bootstrap/css/bootstrap.css">
    <script src="libs/jquery.min.js"></script>
<!--    <script src="js/car-data.js"></script>-->

</head>

<body>
    <!-- 头部开始 -->
    <div class="header">
        <div class="d-flex container justify-content-between">
            <div class="header-nav-left">
                <a href="index.html">
                    <i class="iconfont icon-shouye"></i>
                    环球鞋网首页
                </a>
            </div>
            <div class="header-nav-right d-flex">
                <div class="nav-item" id="sessionChange">你好，请先
                    <a href="login.html">登录</a>
                &nbsp
                <a href="regist.html">
                注册
                </a>
                </div>
                <div class="nav-spacer"></div>
                <a href="myorder.html" class="nav-item">我的订单</a>
                <div class="nav-spacer"></div>
                <a href="information.html" class="nav-item">个人中心</a>
                <div class="nav-spacer"></div>
                <a href="#" class="nav-item">帮助中心</a>
            </div>
        </div>
    </div>
    <!-- 头部结束 -->
    <!-- 头部2开始 -->
    <div class="header-two my-3">
        <div class="container d-flex justify-content-between">
            <div class="login-left">
                <img src="images/logo.png" alt="logo">
            </div>
            <div class="schedule-box">
                <ul class="schedule-list">
                    <li class="schedule-list1">
                        <span class="schedule-list-active"></span>
                        <span class="schedule-font">我的购物车</span>
                    </li>
                    <li class="schedule-list2">
                        <span class="schedule-list-active2 auto"></span>
                        <span class="schedule-font">确认订单信息</span>
                    </li>
                    <li class="schedule-list3">
                        <span class="schedule-list-active2 fl-r"></span>
                        <span class="schedule-font">付款，完成购买</span>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- 头部2结束 -->
    <!--路径导航开始-->
    <div id="navPath" class="container">
        <p>
            您当前的位置 :&nbsp&nbsp&nbsp
            <a href="index.html">首页</a>
        </p>
        <i>/</i>
        <a>我的购物车</a>
    </div>
    <!--路径导航结束-->
    <div class="car-container" style="display: none">
        <div class="container px-0">
            <!-- 购物车主要核心区域 -->
            <div class="cart-warp">
                <!-- 头部全选模块 -->
                <div class="cart-thead d-flex text-center">
                    <div class="t-checkbox col-1">
                        <input type="checkbox" name=""  class="checkall"> 全选
                    </div>
                    <div class="col-2">商品图片</div>
                    <div class="col-1">标题</div>
                    <div class="col-1">商品参数</div>
                    <div class="col-2">单价</div>
                    <div class="col-2">数量</div>
                    <div class="col-2">小计</div>
                    <div class="col-1">操作</div>
                </div>
                <!-- 商品详细模块 -->
                <div class="container px-0 text-center" id="cart-list">
                    <div class="cart-item check-cart-item d-flex">
                        <div class="p-checkbox col-1 align-self-center">
                            <input type="checkbox" name=""  checked class="j-checkbox">
                        </div>
                        <div class="p-goods col-2 align-self-center">
                            <div class="p-img">
                                <img src="images/item1_small.png" alt="">
                            </div>
                        </div>
                        <div class="p-msg col-1 align-self-center">乔丹</div>
                        <div class="col-1 align-self-center">32码</div>
                        <div class="p-price col-2 align-self-center">￥520</div>
                        <div class="p-num col-2 d-flex justify-content-center align-self-center">
                            <div class="quantity-form">
                                <a href="javascript:;" class="decrement">-</a>
                                <input type="text" class="itxt" value="1">
                                <a href="javascript:;" class="increment">+</a>
                            </div>
                        </div>
                        <div class="p-sum col-2 align-self-center">￥520</div>
                        <div class="p-action col-1 align-self-center">
                            <button class="noselect"><span class="text">删除</span><span class="icon"><svg
                                        xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                        <path
                                            d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z">
                                        </path>
                                    </svg></span></button>
                        </div>
                    </div>
                </div>
                <!-- 结算模块 -->
                <div class="cart-floatbar d-flex text-center justify-content-between" id="carNav">
                    <div class="cart-wrapper d-flex col-4 py-1">
                        <div class="select-all col-3">
                            <input type="checkbox" name=""  class="checkall">全选
                        </div>
                        <div class="operation col-6">
                            <a href="javascript:;" class="remove-batch"> 删除选中的商品</a>
                            <a href="javascript:;" class="clear-all">清理购物车</a>
                        </div>
                    </div>
                    <div class="d-flex col-4 pt-0">
                        <div class="amount-sum col-4 py-1">已经选<em>1</em>件商品
                            <i class="iconfont icon-xiangshang"></i>
                        </div>
                        <div class="price-sum col-4 py-1">总价:<em>￥520</em></div>
                        <div class="btn-area col-4 text-center pt-1">去结算</div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 结算模块 -->
        <div class="cart-floatbar fixed-bottom-container position-fixed bottom-0 w-100" id="carNavFixed">
            <!-- 结算模块 -->
            <div class="container px-0">
                <div class="cart-floatbar d-flex text-center justify-content-between">
                    <div class="cart-wrapper d-flex col-4 py-1">
                        <div class="select-all col-3">
                            <input type="checkbox" name="" id="" class="checkall">全选
                        </div>
                        <div class="operation col-6">
                            <a href="javascript:;" class="remove-batch"> 删除选中的商品</a>
                            <a href="javascript:;" class="clear-all" onclick="clear()">清理购物车</a>
                        </div>
                    </div>
                    <div class="d-flex col-4 pt-0">
                        <div class="amount-sum col-4 py-1">已经选<em>1</em>件商品
                            <i class="iconfont icon-xiangshang"></i>
                        </div>
                        <div class="price-sum col-4 py-1">总价:<em>￥520</em></div>
                        <div class="btn-area col-4 text-center pt-1">去结算</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container px-0 mt-5 car-nothing-container">
        <div class="d-flex justify-content-center align-content-center">
            <div class="nothing-img">
                <img src="images/car.png" alt="">
            </div>
            <div>
                <div class="noting-text">
                    <p>购物车空空如也,</p>
                    <p>快去抢购心仪的商品吧~</p>
                </div>
                <div class="nothing-btn">
                    <button>
                        <a href="index.html" class="nothing-btn-index">立即抢购</a>
                    </button>
                    <button>
                        <a href="myorder.html">查看订单</a>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <!-- Flexbox container for aligning the toasts -->
    <div class="w-100  h-auto d-flex position-fixed top-0 mt-5">
        <div class="toast position-relative mx-auto" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header justify-content-between">
                <div>
                    <strong class="mr-auto">通知</strong>
                </div>
                <div>
                    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
            <div class="toast-body">
                删除成功
            </div>
        </div>
    </div>
    <div style="height: 100px;"></div>
</body>
<!--<script src="js/car.js"></script>-->
<script>
    let myToast = bootstrap.Toast.getOrCreateInstance($(".toast"));
    let items=null;
    let total = 0.00;
    fetch(`show.car`).then(response=>response.json()).then(data=>{
        if(data.flag){
            console.log(data.data)
            console.log(data.flag)
            // 存在数据响应
            // if(data.data.items!=null && data.data.items.length>0)
            if(data.data!=null){   //存在数据
                loadCartList(data.data.items,data.data.total);

                $(".payment").on("click",function (){
                    createOrder();
                })
                let createOrder = function (){
                    //拿到选择商品的数据
                    let arr = [];
                    $(".cart-item").each(function (i,ele){
                        let obj = {};
                        if($(ele).children(".p-checkbox").children("input").prop("checked")==true){
                            let pid = Number(data.data.items[i].product.id);
                            let size = Number(data.data.items[i].size);
                            let shoppingPrice = Number(data.data.items[i].shoppingPrice);
                            let qty = Number(data.data.items[i].qty);
                            obj={pid,size,shoppingPrice,qty}
                            arr.push(obj);
                            console.log(data.data.items[i].product.id);
                            console.log(data.data.items[i].size);
                        }
                    })
                    console.log(arr);
                    let resultCar = {
                        "item":arr
                    }
                    fetch("create.order",{
                        method:"POST",
                        contentType: "application/json",
                        body:JSON.stringify(resultCar)
                    }).then(response=>response.json()).then(data=>{
                        console.log(data);
                        if(data.flag){
                            //将数据存储到sessionStorage中
                            sessionStorage.setItem("shopping.orderInfo",JSON.stringify(data.data));
                            location.href="order.html";
                        }else{
                            let toastBody = document.querySelector(".toast-body");
                            toastBody.innerHTML = data.message;
                            myToast.show();
                            setTimeout(function (){
                                if (data.code==400404){
                                    location.href="login.html";
                                }
                            },1500);

                        }
                    })
                }


                $(".car-container").css("display","block").siblings(".car-nothing-container").css("display","none");
            }else{
                //购物车中不存在数据
                $(".car-nothing-container").css("display","block").siblings(".car-container").css("display","none");
        }}
    })
    let cartList=document.querySelector("#cart-list");
    let carNavFixed=document.querySelector("#carNavFixed");
    let carNav = document.querySelector("#carNav");
    function loadCartList(goodData,total){
        let cartItems = '';
        let settlement01='';
        let settlement02 = ''; //结算
        console.log(goodData);
        console.log(total)
        for(let i = 0; i < goodData.length; i++){
            let p=goodData[i].product;
            let qty=goodData[i].qty;
            let size=goodData[i].size;
            let shoppingPrice = goodData[i].shoppingPrice;
            cartItems+=`
            <div class="cart-item check-cart-item d-flex" pid="${p.id}">
                        <div class="p-checkbox col-1 align-self-center">
                            <input type="checkbox" name="" id="" checked class="j-checkbox">
                        </div>
                        <div class="p-goods col-2 align-self-center">
                            <div class="p-img">
                            <a href="product.html?pid=${p.id}">
                                <img src="${p.pimage}" alt="">
                            </a>
                            </div>
                        </div>
                        <div class="p-msg col-1 align-self-center">${p.name}</div>
                        <div class="p-size col-1 align-self-center">${size}码</div>
                        <div class="p-price col-2 align-self-center">￥${shoppingPrice}</div>
                        <div class="p-num col-2 d-flex justify-content-center align-self-center">
                            <div class="quantity-form">
                                <a href="javascript:;" class="decrement">-</a>
                                <input type="text" class="itxt" value="${qty}">
                                <a href="javascript:;" class="increment">+</a>
                            </div>
                        </div>
                        <div class="p-sum col-2 align-self-center">￥${shoppingPrice*qty}</div>
                        <div class="p-action col-1 align-self-center">
                            <button class="noselect" onclick="remove(${p.id},${size})"><span class="text">删除</span><span class="icon"><svg
                                        xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                        <path
                                            d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z">
                                        </path>
                                    </svg></span></button>
                        </div>
                    </div>
            `
        }
        settlement01 = `
        <div class="cart-wrapper d-flex col-4 py-1">
                        <div class="select-all col-3">
                            <input type="checkbox" name="" id="" class="checkall">全选
                        </div>
                        <div class="operation col-6">
                            <a href="javascript:;" class="remove-batch"> 删除选中的商品</a>
                            <a href="javascript:;" class="clear-all">清理购物车</a>
                        </div>
                    </div>
                    <div class="d-flex col-4 pt-0">
                        <div class="amount-sum col-4 py-1">已经选<em>0</em>件商品
                            <i class="iconfont icon-xiangshang"></i>
                        </div>
                        <div class="price-sum col-4 py-1">总价:<em>￥0.00</em></div>
                        <div class="btn-area col-4 text-center pt-1 payment">去结算</div>
                    </div>`;
        settlement02 =`<!-- 结算模块 -->
                <div class="container px-0">
                <div class="cart-floatbar d-flex text-center justify-content-between">
                    <div class="cart-wrapper d-flex col-4 py-1">
                        <div class="select-all col-3">
                            <input type="checkbox" name="" id="" class="checkall">全选
                        </div>
                        <div class="operation col-6">
                            <a href="javascript:;" class="remove-batch"> 删除选中的商品</a>
                            <a href="javascript:;" class="clear-all">清理购物车</a>
                        </div>
                    </div>
                    <div class="d-flex col-4 pt-0">
                        <div class="amount-sum col-4 py-1">已经选<em>0</em>件商品
                            <i class="iconfont icon-xiangshang"></i>
                        </div>
                        <div class="price-sum col-4 py-1">总价:<em>￥0.00</em></div>
                        <div class="btn-area col-4 text-center pt-1 payment">去结算</div>
                    </div>
                </div>
            </div>`;
        cartList.innerHTML = cartItems;
        carNav.innerHTML = settlement01;
        carNavFixed.innerHTML = settlement02;

        car();
        //清空购物车
        $(".clear-all").click(function (){
            clear();
        })
        // $(".payment").click(function (){
        //
        // })


    }

    function clear(){
        fetch("clear.car").then(response=>response.json()).then(data=>{
            if(data.flag){
                let toastBody = document.querySelector(".toast-body");
                toastBody.innerHTML = data.message;
                myToast.show();
            }
        })
    }

    function remove(pid,size){
        fetch(`remove.car?pid=${pid}&size=${size}`).then(response=>response.json()).then(data=>{
            if(data.flag){
                let toastBody = document.querySelector(".toast-body");
                toastBody.innerHTML = data.message;
                myToast.show();
            }
        })
    }


    function car(){
        // 1. 全选 全不选功能模块
        // 就是把全选按钮（checkall）的状态赋值给 三个小的按钮（j-checkbox）就可以了
        // 事件可以使用change
        $(".checkall").change(function() {
            $(".j-checkbox, .checkall").prop("checked", $(this).prop("checked"));
            if ($(this).prop("checked")) {
                // 让所有的商品添加 check-cart-item 类名
                $(".cart-item").addClass("check-cart-item");
            } else {
                // check-cart-item 移除
                $(".cart-item").removeClass("check-cart-item");
            }
            getSum();
            changeTotalPrice();
            hiddenCar();
        });
        // 2. 如果小复选框被选中的个数等于3 就应该把全选按钮选上，否则全选按钮不选。
        checkedInput();
        function checkedInput(){
            if ($(".j-checkbox:checked").length === $(".j-checkbox").length) {
                $(".checkall").prop("checked", true);
            } else {
                $(".checkall").prop("checked", false);
            }
            if ($(this).prop("checked")) {
                // 让当前的商品添加 check-cart-item 类名
                $(this).parents(".cart-item").addClass("check-cart-item");
            } else {
                // check-cart-item 移除
                $(this).parents(".cart-item").removeClass("check-cart-item");
            }
        }
        $(".j-checkbox").on("change",function(){
            if ($(this).prop("checked")) {
                // 让当前的商品添加 check-cart-item 类名
                $(this).parents(".cart-item").addClass("check-cart-item");
            } else {
                // check-cart-item 移除
                $(this).parents(".cart-item").removeClass("check-cart-item");
            }
            changeTotalPrice();
            hiddenCar();
            checkedInput();
            getSum();
        });
        // 3. 增减商品数量模块 首先声明一个变量，当我们点击+号（increment），就让这个值++，然后赋值给文本框。
        $(".increment").click(function() {
            // 得到当前兄弟文本框的值
            var n = $(this).siblings(".itxt").val();
            n++;
            $(this).siblings(".itxt").val(n);
            // 3. 计算小计模块 根据文本框的值 乘以 当前商品的价格  就是 商品的小计
            // 当前商品的价格 p
            var p = $(this).parents(".p-num").siblings(".p-price").html();
            // console.log(p);
            p = p.substr(1);
            console.log(p);
            var price = (p * n).toFixed(2);
            // 小计模块
            // toFixed(2) 可以让我们保留2位小数
            $(this).parents(".p-num").siblings(".p-sum").html("￥" + price);
            getSum();
        });
        $(".decrement").click(function() {
            // 得到当前兄弟文本框的值
            var n = $(this).siblings(".itxt").val();
            if (n == 1) {
                return false;
            }
            // console.log(n);
            n--;
            $(this).siblings(".itxt").val(n);
            // var p = $(this).parent().parent().siblings(".p-price").html();
            // parents(".p-num") 返回指定的祖先元素
            var p = $(this).parents(".p-num").siblings(".p-price").html();
            p = p.substr(1);
            // 小计模块
            $(this).parents(".p-num").siblings(".p-sum").html("￥" + (p * n).toFixed(2));
            getSum();
        });
        //  4. 用户修改文本框的值 计算 小计模块
        $(".itxt").change(function() {
            // 先得到文本框的里面的值 乘以 当前商品的单价
            var n = $(this).val();
            // 当前商品的单价
            var p = $(this).parents(".p-num").siblings(".p-price").html();
            // console.log(p);
            p = p.substr(1);
            $(this).parents(".p-num").siblings(".p-sum").html("￥" + (p * n).toFixed(2));
            getSum();
        });

        function changeTotalPrice(){
            if ($(".j-checkbox:checked").length==0){
                $(".amount-sum em").text(0);
                $(".price-sum em").text("￥" + 0.00);
            }
        }
        // 5. 计算总计和总额模块
        getSum();

        function getSum() {
            var count = 0; // 计算总件数
            var money = 0; // 计算总价钱
            $(".cart-item").each(function (i,ele){
                if($(ele).children(".p-checkbox").children("input").prop("checked")==true){
                    count += parseInt($(ele).find(".itxt").val());
                    $(".amount-sum em").text(count);
                    money += parseFloat($(ele).find(".p-sum").text().substr(1));
                    $(".price-sum em").text("￥" + money.toFixed(2));
                }
            })
        }
        // 6. 删除商品模块
        // (1) 商品后面的删除按钮
        $(".noselect").click(function() {
            // 删除的是当前的商品
            $(this).parents(".cart-item").remove();
            getSum();
            fixedNavBottom()
            if($(".cart-item").length==0){
                $(".checkall").prop("checked", false);
            }
            changeTotalPrice();
            hiddenCar()
        });
        // (2) 删除选中的商品
        $(".remove-batch").click(function() {
            $(".cart-item").each(function (i,ele){
                        if($(ele).find(".p-checkbox").find("input").prop("checked")==true){
                            remove($(ele).attr("pid"),$(ele).find(".p-size").text());
                        }
                    })
            // 删除的是小的复选框选中的商品
            $(".j-checkbox:checked").parents(".cart-item").remove();
            getSum();
            fixedNavBottom()
            changeTotalPrice();
            hiddenCar()
        });
        // (3) 清空购物车 删除全部商品
        $(".clear-all").click(function() {
            $(".cart-item").remove();
            getSum();
            fixedNavBottom()
            changeTotalPrice();
            hiddenCar()
        })

        //如果没有商品 则隐藏条目
        function hiddenCar(){
            if($(".cart-item").length==0){
                $(".car-nothing-container").css("display","block").siblings(".car-container").css("display","none");
            }else{
                $(".car-container").css("display","block").siblings(".car-nothing-container").css("display","none");
            }
        }
        //控制底部固定购物车
        function fixedNavBottom(){
            if($(document).scrollTop()+document.documentElement.clientHeight >= $("#carNav").offset().top+45){
                $("#carNavFixed").css("display","none");
            }else{
                $("#carNavFixed").css("display","block");
            }
        }
        $(window).scroll(function(){
            fixedNavBottom()
        })
        //商品条目小于三不显示
        if($(".cart-item").length<3){
            $("#carNavFixed").css("display","none");
        }
        //轻量弹框 当点击关闭按钮时关闭
        $(".close").on("click",function(){
            myToast.hide();
        })
    }
    stateManagement();
    function stateManagement() {
        //状态管理
        //判断用户是否登录
        let userInfo = sessionStorage.getItem("shopping.userInfo");
        let User = ``;
        if(userInfo){
            let user = JSON.parse(userInfo);
            User = `你好，
                <a href="#">${user.username}</a>
                &nbsp
                <a href="javascript:;" id="quit">
                    <i class="iconfont icon-tuichu"></i>
                    退出
                </a>
            `
        }else{
            User = `你好，请先
                <a href="login.html">登录</a>
                &nbsp
                <a href="regist.html">
                    注册
                </a>
            `
        }
        $("#sessionChange").html(`${User}`);
    }
    $("#quit").on("click",function(){
        sessionStorage.removeItem('shopping.userInfo');
        stateManagement();
        location.reload();
    })
</script>
</html>